package com.nulldev.util.web.flexibleKit.flexRenderer.paths.subgens;

import com.nulldev.util.VariableAPI.ArrayUtils;
import com.nulldev.util.VariableAPI.StringsUtil;
import com.nulldev.util.graphics.renderIt.api.renderItGraphicsInterface;
import com.nulldev.util.graphics.renderIt.api.core.RITFont;
import com.nulldev.util.graphics.renderIt.renderer.global.rColor;
import com.nulldev.util.graphics.renderIt.util.renderItUtils;
import com.nulldev.util.graphics.renderIt.util.renderPosition;
import com.nulldev.util.web.flexibleKit.flexRenderer.FlexEnvironment;
import com.nulldev.util.web.flexibleKit.flexRenderer.paths.PathGenerator;
import com.nulldev.util.web.flexibleKit.flexRenderer.styling.fonts.flexFontManager;
import com.nulldev.util.web.flexibleKit.general.RenderOperation;
import com.nulldev.util.web.flexibleKit.global.GlobalRendererSettings;
import com.nulldev.util.web.flexibleKit.jfvParse.Node;

public class ParagraphGenerator implements PathGenerator {

	@Override
	public RenderOperation generate(final Node n, final PathGenerationFlags... flags) {
		final RenderOperation ri = new RenderOperation() {

			@Override
			public renderPosition doRender(final renderItGraphicsInterface i, final renderPosition rp, final FlexEnvironment env) {
				final int fontSize = GlobalRendererSettings.SCALE_TEXT_AUTOMATICALLY ? i.viewport_getWidth() / 32 : flexFontManager.getFontSize("paragraph");
				final String s = n.getTextContent();
				if (isBlankLine(s))
					return rp;
//				if (!ArrayUtils.contains(flags, PathGenerationFlags.RENDER_INLINE)) {
//					rp.setAndResetX();
//				}
				RITFont font = env.fontCache
						.getFont(ArrayUtils.contains(flags, PathGenerationFlags.USE_MONOSPACED_FONT) ? "monospace-paragraph" : "sans-serif-paragraph");
				if (ArrayUtils.contains(flags, PathGenerationFlags.USE_BOLD_TEXT))
					font = font.deriveToStyle(RITFont.RIT_FONT_VARIANT_BOLD);
				if (ArrayUtils.contains(flags, PathGenerationFlags.USE_ITALIC_TEXT))
					font = font.deriveToStyle(RITFont.RIT_FONT_VARIANT_ITALIC);
				final int offset = rp.getX();
				final int inc = i.text_scalable(s, rp.getX(), rp.appendGetY(fontSize), offset, font, rColor.BLACK);
				if (ArrayUtils.contains(flags, PathGenerationFlags.RENDER_INLINE)) {
					return rp.addX(renderItUtils.guessTextWidth(fontSize, s));
				} else {
					return rp.addY(inc).setAndResetX();
				}
//				i.submitExtensionData(RequestableExtensions.FR_EXT_PREV_POSITION, rp); // FIXME: Implement proper reverting into position
//				i.requestViewportHeight(rp.getY());
			}

			@Override
			public Node operationFor() {
				return n;
			}

			@Override
			public boolean keepInline() {
				return ArrayUtils.contains(flags, PathGenerationFlags.RENDER_INLINE);
			}
		};
		return ri;
	}

	public static boolean isBlankLine(final String s) {
		if (s.equalsIgnoreCase("\n") || s.equalsIgnoreCase("\t"))
			return true;
		if (s.startsWith("\\u000a") && s.endsWith("\\u000a"))
			return true;
		return StringsUtil.isBlank(s);
	}
}
